package cn.sytton.taffe.file.controller;

import cn.sytton.taffe.framework.util.OutputStreamUtil;
import cn.sytton.taffe.framework.util.ServletUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * 下载导入模版控制类
 *
 * @author skyrock
 */
@Tag(name = "导入模版")
@RestController
@RequestMapping("/template")
public class TemplateController {

    @Operation(summary = "下载导入模版")
    @Parameter(name = "name", description = "文件名", in = ParameterIn.PATH, required = true)
    @GetMapping(value = "/download/{name}")
    public void downloadTemplate(@PathVariable String name) throws IOException {

        Resource resource = new ClassPathResource("template/"+name);
//        File file = resource.getFile();
//        String filename = file.getName();

        // 将文件写入输入流
//        FileInputStream fileInputStream = new FileInputStream(resource.getInputStream());
        InputStream fis = new BufferedInputStream(resource.getInputStream());
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();

        HttpServletResponse response = ServletUtil.getResponse();
        assert response != null;
        OutputStreamUtil.setDownloadHeader(response, name, buffer.length);
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        outputStream.write(buffer);
        outputStream.flush();
    }
}
